using System;
using System.Collections.Generic;
using System.Drawing;
using System.Globalization;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using Lyh.Train.Data;
using Lyh.Train.Common.Http;
using Lyh.Train.Common.Convertor;

namespace Lyh.Train.Service
{
    public class TicketService
    {
        public CookieContainer Cookies = new CookieContainer();

        public TicketService(CookieContainer cookies)
        {
            this.Cookies = cookies;
        }

        public string GetUserName()
        {
            HttpClient httpClient = new HttpClient(this.Cookies);
            if (Context.Proxy != "")
            {
                httpClient.Proxy = new WebProxy(Context.Proxy);
            }
            string url = "https://kyfw.12306.cn/otn/index/initMy12306";
            string str = httpClient.Get(url, "", "", "", "", "get");
            string str2 = HtmlHelper.GetContent(str, "user_name=", ";").Replace("'", "");
            return Regex.Unescape(str2);
        }

        public QueryTicketResponseInfo QueryLeftTicketDTO(string train_date, string from_station, string to_station)
        {
            try
            {
                HttpClient httpClient = new HttpClient(this.Cookies);
                if (Context.Proxy != "")
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                string text = "https://kyfw.12306.cn/otn/leftTicket/query?leftTicketDTO.train_date={0}&leftTicketDTO.from_station={1}&leftTicketDTO.to_station={2}&purpose_codes=ADULT";
                text = string.Format(text, train_date, from_station, to_station);
                string text2 = httpClient.Get(text, "", "", "", "", "get");
                QueryTicketResponseInfo result;
                if (text2 != "")
                {
                    QueryTicketResponseInfo queryTicketResponseInfo = JsonHelper.JsonDeserialize<QueryTicketResponseInfo>(text2);
                    result = queryTicketResponseInfo;
                }
                else
                {
                    result = null;
                }
                return result;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public GetPassengerDTOsResponseInfo GetMyPassengers()
        {
            HttpClient httpClient = new HttpClient(this.Cookies);
            if (Context.Proxy != "")
            {
                httpClient.Proxy = new WebProxy(Context.Proxy);
            }
            string url = "https://kyfw.12306.cn/otn/confirmPassenger/getPassengerDTOs";
            string text = httpClient.Get(url, "", "", "", "", "get");
            GetPassengerDTOsResponseInfo result;
            if (text != "")
            {
                GetPassengerDTOsResponseInfo getPassengerDTOsResponseInfo = JsonHelper.JsonDeserialize<GetPassengerDTOsResponseInfo>(text);
                result = getPassengerDTOsResponseInfo;
            }
            else
            {
                result = null;
            }
            return result;
        }

        public void CheckUser()
        {
            HttpClient httpClient = new HttpClient(this.Cookies);
            if (Context.Proxy != "")
            {
                httpClient.Proxy = new WebProxy(Context.Proxy);
            }
            string url = "https://kyfw.12306.cn/otn/login/checkUser";
            string text = httpClient.Post(url, "_json_att=", "kyfw.12306.cn", "https://kyfw.12306.cn", "https://kyfw.12306.cn/otn/leftTicket/init", "post");
        }

        public bool SubmitOrderRequest(string secretStr, QueryEntity qe, ref string msg)
        {
            HttpClient httpClient = new HttpClient(this.Cookies);
            if (Context.Proxy != "")
            {
                httpClient.Proxy = new WebProxy(Context.Proxy);
            }
            string text = "https://kyfw.12306.cn/otn/leftTicket/submitOrderRequest";
            string text2 = "secretStr={0}&train_date={1}&back_train_date={2}&tour_flag=dc&purpose_codes=ADULT&query_from_station_name={3}&query_to_station_name={4}&undefined";
            object[] args = new object[]
            {
                secretStr,
                qe.train_date,
                qe.train_date,
                qe.from_station_telecode_name,
                qe.to_station_telecode_name
            };
            text2 = string.Format(text2, args);
            text = text + "?" + text2;
            string str = httpClient.Get(text, "kyfw.12306.cn", "https://kyfw.12306.cn", "https://kyfw.12306.cn/otn/leftTicket/init", "", "get").Replace("\"", "");
            string content = HtmlHelper.GetContent(str, "status:", ",");
            msg = HtmlHelper.GetContent(str, "messages:", ",").Replace("[", "").Replace("]", "");
            return content == "true";
        }

        public TicketInfo GetTicketInfo()
        {
            TicketInfo result;
            try
            {
                TicketInfo ticketInfo = null;
                HttpClient httpClient = new HttpClient(this.Cookies);
                if (Context.Proxy != "")
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                string url = "https://kyfw.12306.cn/otn/confirmPassenger/initDc";
                string str = httpClient.Get(url, "kyfw.12306.cn", "https://kyfw.12306.cn", "https://kyfw.12306.cn/otn/leftTicket/init", "", "get");
                string text = HtmlHelper.GetContent(str, "'leftDetails':\\[", "],");
                text = Regex.Unescape(text).Replace("'", "");
                string[] array = text.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                if (array.Length > 0)
                {
                    ticketInfo = new TicketInfo();
                    List<TickePriceInfo> list = new List<TickePriceInfo>();
                    for (int i = 0; i < array.Length; i++)
                    {
                        string text2 = array[i];
                        text2 = text2.Replace("(", "#").Replace(")", "#");
                        string[] array2 = text2.Split("#".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                        list.Add(new TickePriceInfo
                        {
                            SeatType = array2[0],
                            Price = array2[1],
                            TicektCnt = array2[2]
                        });
                    }
                    ticketInfo.TicketList = list;
                    ticketInfo.Token = HtmlHelper.GetContent(str, "globalRepeatSubmitToken", ";").Replace("=", "").Replace("'", "").Trim();
                    string text3 = HtmlHelper.GetContent(str, "'queryLeftTicketRequestDTO':", "}");
                    text3 += "}";
                    QueryLeftTicketRequestDTO queryLeftTicketRequestDTO = JsonHelper.FromJson<QueryLeftTicketRequestDTO>(text3);
                    string train_date = queryLeftTicketRequestDTO.train_date;
                    queryLeftTicketRequestDTO.train_date = string.Concat(new string[]
                    {
                        train_date.Substring(0, 4),
                        "-",
                        train_date.Substring(4, 2),
                        "-",
                        train_date.Substring(6)
                    });
                    string checkKey = HtmlHelper.GetContent(str, "'key_check_isChange':", ",").Replace("'", "");
                    string text4 = HtmlHelper.GetContent(str, "'queryLeftTicketRequestDTO':", "};");
                    text4 += "};";
                    string trainLocation = HtmlHelper.GetContent(text4, "'train_location':", "};").Replace("'", "");
                    ticketInfo.CheckKey = checkKey;
                    ticketInfo.TrainLocation = trainLocation;
                    ticketInfo.LeftTicketInfo = queryLeftTicketRequestDTO;
                }
                result = ticketInfo;
            }
            catch
            {
                result = null;
            }
            return result;
        }

        public bool CheckOrderInfo(string token, string vc, List<PassengerInfo> list, ref string msg)
        {
            bool result;
            try
            {
                HttpClient httpClient = new HttpClient(this.Cookies);
                if (Context.Proxy != "")
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                string text = "";
                string text2 = "";
                foreach (PassengerInfo current in list)
                {
                    string str = string.Concat(new string[]
                    {
                        current.SeatType,
                        ",0,",
                        current.TicketType,
                        ",",
                        current.Passenger.passenger_name,
                        ",",
                        current.Passenger.passenger_id_type_code,
                        ",",
                        current.Passenger.passenger_id_no,
                        ",",
                        (current.Passenger.phone_no == null) ? "" : current.Passenger.phone_no,
                        ",N"
                    });
                    text = text + str + "_";
                    string str2 = string.Concat(new string[]
                    {
                        current.Passenger.passenger_name,
                        ",",
                        current.Passenger.passenger_id_type_code,
                        ",",
                        current.Passenger.passenger_id_no,
                        ",",
                        current.Passenger.passenger_type
                    });
                    text2 = text2 + str2 + "_";
                }
                text = HttpUtility.UrlEncode(text);
                text2 = HttpUtility.UrlEncode(text2);
                string text3 = "cancel_flag=2&bed_level_order_num=000000000000000000000000000000&passengerTicketStr={0}&oldPassengerStr={1}&tour_flag=dc&randCode={2}&_json_att=&REPEAT_SUBMIT_TOKEN={3}";
                string url = "https://kyfw.12306.cn/otn/confirmPassenger/checkOrderInfo";
                text3 = string.Format(text3, new object[]
                {
                    text,
                    text2,
                    vc,
                    token
                });
                string text4 = httpClient.Post(url, text3, "kyfw.12306.cn", "https://kyfw.12306.cn", "https://kyfw.12306.cn/otn/confirmPassenger/initDc", "post");
                text4 = text4.Replace("\"", "");
                bool flag = text4.Contains("submitStatus:true");
                if (!flag)
                {
                    msg = HtmlHelper.GetContent(text4, "errMsg:", ",");
                }
                result = flag;
            }
            catch
            {
                result = false;
            }
            return result;
        }

        public CountInfo GetQueueCount(TicketInfo ti, string seatType)
        {
            CountInfo result;
            try
            {
                HttpClient httpClient = new HttpClient(this.Cookies);
                if (Context.Proxy != "")
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                string text = ti.LeftTicketInfo.train_date + " 00:00:00";
                text = Convert.ToDateTime(text).ToString("ddd MMM dd yyyy HH:mm:ss 'GMT'zzz ", CultureInfo.GetCultureInfo("en-US"));
                text = text.Replace("08:00", "0800") + "(中国标准时间)";
                string train_no = ti.LeftTicketInfo.train_no;
                string station_train_code = ti.LeftTicketInfo.station_train_code;
                string ypInfoDetail = ti.LeftTicketInfo.ypInfoDetail;
                string from_station = ti.LeftTicketInfo.from_station;
                string to_station = ti.LeftTicketInfo.to_station;
                string text2 = "00";
                string token = ti.Token;
                string text3 = "train_date={0}&train_no={1}&stationTrainCode={2}&seatType={3}&fromStationTelecode={4}&toStationTelecode={5}&leftTicket={6}&purpose_codes={7}&_json_att=&REPEAT_SUBMIT_TOKEN={8}";
                object[] args = new object[]
                {
                    HttpUtility.UrlEncode(text),
                    train_no,
                    station_train_code,
                    seatType,
                    from_station,
                    to_station,
                    ypInfoDetail,
                    text2,
                    token
                };
                text3 = string.Format(text3, args);
                string url = "https://kyfw.12306.cn/otn/confirmPassenger/getQueueCount";
                string text4 = httpClient.Post(url, text3, "kyfw.12306.cn", "https://kyfw.12306.cn", "https://kyfw.12306.cn/otn/confirmPassenger/initDc", "post");
                text4 = text4.Replace("\"", "");
                string content = HtmlHelper.GetContent(text4, "count:", ",");
                string content2 = HtmlHelper.GetContent(text4, "ticket:", ",");
                string content3 = HtmlHelper.GetContent(text4, "op_2:", ",");
                string content4 = HtmlHelper.GetContent(text4, "countT:", ",");
                string content5 = HtmlHelper.GetContent(text4, "op_1:", "}");
                string cnt = JsFuncitonHelper.GetCnt(content2, seatType);
                result = new CountInfo
                {
                    count = content,
                    countT = content4,
                    op_1 = content5,
                    op_2 = content3,
                    ticket = content2,
                    ticketCnt = cnt
                };
            }
            catch
            {
                result = null;
            }
            return result;
        }

        public bool ConfirmSingleForQueue(TicketInfo ti, string vc, List<PassengerInfo> list, ref string msg)
        {
            bool result;
            try
            {
                msg = string.Empty;
                HttpClient httpClient = new HttpClient(this.Cookies);
                if (Context.Proxy != "")
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                string text = "";
                string text2 = "";
                foreach (PassengerInfo current in list)
                {
                    string str = string.Concat(new string[]
                    {
                        current.SeatType,
                        ",0,",
                        current.TicketType,
                        ",",
                        current.Passenger.passenger_name,
                        ",",
                        current.Passenger.passenger_id_type_code,
                        ",",
                        current.Passenger.passenger_id_no,
                        ",",
                        (current.Passenger.phone_no == null) ? "" : current.Passenger.phone_no,
                        ",N"
                    });
                    text = text + str + "_";
                    string str2 = string.Concat(new string[]
                    {
                        current.Passenger.passenger_name,
                        ",",
                        current.Passenger.passenger_id_type_code,
                        ",",
                        current.Passenger.passenger_id_no,
                        ",",
                        current.Passenger.passenger_type
                    });
                    text2 = text2 + str2 + "_";
                }
                string token = ti.Token;
                string checkKey = ti.CheckKey;
                string ypInfoDetail = ti.LeftTicketInfo.ypInfoDetail;
                text = HttpUtility.UrlEncode(text);
                text2 = HttpUtility.UrlEncode(text2);
                string trainLocation = ti.TrainLocation;
                string text3 = "00";
                string text4 = "passengerTicketStr={0}&oldPassengerStr={1}&randCode={2}&purpose_codes={3}&key_check_isChange={4}&leftTicketStr={5}&train_location={6}&_json_att=&REPEAT_SUBMIT_TOKEN={7}";
                text4 = string.Format(text4, new object[]
                {
                    text,
                    text2,
                    vc,
                    text3,
                    checkKey,
                    ypInfoDetail,
                    trainLocation,
                    token
                });
                string url = "https://kyfw.12306.cn/otn/confirmPassenger/confirmSingleForQueue";
                string text5 = httpClient.Post(url, text4, "kyfw.12306.cn", "https://kyfw.12306.cn", "https://kyfw.12306.cn/otn/confirmPassenger/initDc", "post");
                bool flag = text5.Contains("submitStatus:true");
                if (!flag)
                {
                    msg = HtmlHelper.GetContent(text5, "errMsg:", ",");
                }
                result = flag;
            }
            catch
            {
                result = false;
            }
            return result;
        }

        public QueryWaitTimeResult QueryOrderWaitTime(string token)
        {
            QueryWaitTimeResult result;
            try
            {
                HttpClient httpClient = new HttpClient(this.Cookies);
                if (Context.Proxy != "")
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                string url = "https://kyfw.12306.cn/otn/confirmPassenger/queryOrderWaitTime?tourFlag=dc&_json_att=&REPEAT_SUBMIT_TOKEN=" + token;
                string str = httpClient.Get(url, "kyfw.12306.cn", "https://kyfw.12306.cn", "https://kyfw.12306.cn/otn/confirmPassenger/initDc", "", "get");
                string jsonStr = HtmlHelper.GetContent(str, "\"data\":", "},") + "}";
                QueryWaitTimeResult queryWaitTimeResult = JsonHelper.FromJson<QueryWaitTimeResult>(jsonStr);
                result = queryWaitTimeResult;
            }
            catch
            {
                result = null;
            }
            return result;
        }

        public List<TrainDetails> GetTrainDetails(string train_no, string start_station, string aim_station, string date)
        {
            List<TrainDetails> result;
            try
            {
                HttpClient httpClient = new HttpClient(this.Cookies);
                if (Context.Proxy != "")
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                List<TrainDetails> list = new List<TrainDetails>();
                string text = "https://kyfw.12306.cn/otn/czxx/queryByTrainNo?";
                string text2 = string.Concat(new string[]
                {
                    "train_no=",
                    train_no,
                    "&from_station_telecode=",
                    start_station,
                    "&to_station_telecode=",
                    aim_station,
                    "&depart_date=",
                    date
                });
                text2 = string.Format(text2, new object[]
                {
                    train_no,
                    start_station,
                    aim_station,
                    date
                });
                text += text2;
                string str = httpClient.Get(text, "", "", "", "", "get");
                string text3 = HtmlHelper.GetContent(str, "\"data\":{\"data\":", "]}");
                text3 += "]";
                list = JsonHelper.FromJson<List<TrainDetails>>(text3);
                result = list;
            }
            catch
            {
                result = null;
            }
            return result;
        }

        #region --自动提交订单四个步骤--

        public ServerResponseResult<AutoSubmitOrderRequestData> AutoSubmitOrderRequest(QueryLeftNewDTOData train, QueryEntity queryEntity, List<PassengerDTOs> passengers)
        {
            try
            {
                var passengerTicketStr = new StringBuilder();
                var oldPassengerStr = new StringBuilder();

                foreach (var passenger in passengers)
                {
                    passengerTicketStr.AppendFormat("{0},0,1,{1},{2},{3},{4},N_", queryEntity.SeatType.Value, passenger.passenger_name, passenger.passenger_id_type_code, passenger.passenger_id_no, passenger.mobile_no);
                    oldPassengerStr.AppendFormat("{0},{1},{2},1_", passenger.passenger_name, passenger.passenger_id_type_code, passenger.passenger_id_no);
                }

                var dic = new Dictionary<string, string>
                {
                    {"secretStr", train.secretStr},
                    {"train_date", queryEntity.train_date},
                    {"tour_flag", "dc"},
                    {"purpose_codes", "ADULT"},
                    {"query_from_station_name", queryEntity.from_station_telecode_name},
                    {"query_to_station_name", queryEntity.to_station_telecode_name},
                    {"", ""},
                    {"cancel_flag", "2"},
                    {"bed_level_order_num", "000000000000000000000000000000"},
                    {"passengerTicketStr", passengerTicketStr.ToString().TrimEnd('_')},
                    {"oldPassengerStr", oldPassengerStr.ToString()}
                };
                var httpClient = new HttpClient(Context.Cookies);
                if (!string.IsNullOrWhiteSpace(Context.Proxy))
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                var data = httpClient.CreateParameter(dic);
                var json = httpClient.Post(Context.AutoSubmitOrderRequestUrl, data, Context.Host, Context.Origin, Context.LeftTicketReferer, Context.HttpMethodPost);
                var obj = JsonHelper.FromJson<ServerResponseResult<AutoSubmitOrderRequestData>>(json);
                return obj;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public ServerResponseResult<GetQueueCountAsyncData> GetQueueCountAsync(QueryLeftNewDTOData train, QueryEntity queryEntity, List<PassengerDTOs> passengers, Token token)
        {
            try
            {
                var dic = new Dictionary<string, string>
            {
                {"train_date", (Convert.ToDateTime(queryEntity.train_date).ToString("ddd MMM dd yyy ", DateTimeFormatInfo.InvariantInfo) + DateTime.Now.ToString("HH:mm:ss").Replace(":", "%3A") + " GMT%2B0800  (China Standard Time)").Replace(' ', '+')},
                {"train_no", train.queryLeftNewDTO.train_no},
                {"stationTrainCode", train.queryLeftNewDTO.station_train_code},
                {"seatType", queryEntity.SeatType.Value},
                {"fromStationTelecode", train.queryLeftNewDTO.from_station_telecode},
                {"toStationTelecode", train.queryLeftNewDTO.end_station_telecode},
                {"leftTicket", token.ShortToken},
                {"purpose_codes", "ADULT"},
                {"_json_att", ""}
            };
                var httpClient = new HttpClient(Context.Cookies);
                if (!string.IsNullOrWhiteSpace(Context.Proxy))
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                var data = httpClient.CreateParameter(dic);
                var json = httpClient.Post(Context.GetQueueCountAsyncUrl, data, Context.Host, Context.Origin, Context.LeftTicketReferer, Context.HttpMethodPost);
                var obj = JsonHelper.FromJson<ServerResponseResult<GetQueueCountAsyncData>>(json);
                return obj;
            }
            catch (Exception)
            {
                return null;
            }
        }

        public Image GetOrderRandCodeImage()
        {
            var url = string.Format("{0}&{1}", Context.LoginRandCodeUrl, new Random().NextDouble());
            var img = RandCodeHelper.GetRandCodeImage(url);
            return img;
        }

        public ServerResponseResult<ConfirmSingleForQueueAsysData> ConfirmSingleForQueueAsys(string passengerTicketStr, string oldPassengerStr, Token token, string randCode)
        {
            try
            {
                var dic = new Dictionary<string, string>
            {
                {"passengerTicketStr", HttpUtility.UrlEncode((passengerTicketStr.TrimEnd('_'))).ToUpper()},
                {"oldPassengerStr", HttpUtility.UrlEncode(oldPassengerStr).ToUpper()},
                {"randCode", randCode},
                {"purpose_codes", "ADULT"},
                {"key_check_isChange", token.LongToken},
                {"leftTicketStr", token.ShortToken},
                {"train_location", token.Q},
                {"_json_att", ""}
            };
                var httpClient = new HttpClient(Context.Cookies);
                if (!string.IsNullOrWhiteSpace(Context.Proxy))
                {
                    httpClient.Proxy = new WebProxy(Context.Proxy);
                }
                var data = httpClient.CreateParameter(dic);
                var json = httpClient.Post(Context.ConfirmSingleForQueueAsysUrl, data, Context.Host, Context.Origin, Context.LeftTicketReferer, Context.HttpMethodPost);
                var obj = JsonHelper.FromJson<ServerResponseResult<ConfirmSingleForQueueAsysData>>(json);
                return obj;
            }
            catch (Exception)
            {
                return null;
            }
        }

        #endregion

        /// <summary>
        /// 查询未完成订单
        /// </summary>
        /// <returns></returns>
        public ServerResponseResult<QueryMyOrderNoCompleteData> QueryMyOrderNoComplete()
        {
            var httpClient = new HttpClient(Context.Cookies);
            if (!string.IsNullOrWhiteSpace(Context.Proxy))
            {
                httpClient.Proxy = new WebProxy(Context.Proxy);
            }
            var json = httpClient.Get(Context.QueryMyOrderNoCompleteUrl, "", "", "", "", Context.HttpMethodGet);
            var obj = JsonHelper.FromJson<ServerResponseResult<QueryMyOrderNoCompleteData>>(json);
            return obj;
        }
    }
}